<!-- 双向绑定选择器 -->
<template>
	<picker @change="handleChange" mode="selector" :value="index" :range="options" :range-key="rangeKey"
		:style="currentValue ? '' : 'color:#808080;'" :disabled="disabled">
		{{currentValue || placeholoder}}
	</picker>
</template>

<script setup lang="ts">
	import { ref, reactive, computed, watch ,onMounted} from 'vue'
	const emit = defineEmits(['input', 'change'])
	const props = defineProps({
		values: {
			default: ""
		},
		options: {
			type:Array,
			default:[]
		},
		rangeKey: String,
		rangeValue: {
			type: String,
			default: "value"
		},
		placeholoder: {
			type: String,
			default: "请选择"
		},
		disabled: {
			type: Boolean,
			default: false,
		}
	})
	onMounted(()=>{
		if(props.values){
			index.value = props.rangeKey ? props.options.findIndex(item => item[props.rangeValue] == props.values) : props.options.findIndex(item => item == props.values);
		}
		
	})
	const index = ref(-1)
	const currentValue = computed(() => {
		if (props.rangeKey) {
			return index.value == -1 ? "" : props.options[index.value][props.rangeKey]
		} else {
			return props.options[index.value]
		}
	})

	
	
	const handleChange = (e : any) => {
		
		index.value = e.detail.value
		
		if (index.value > -1) {
			let currentValue = props.rangeKey ? props.options[index.value][props.rangeValue] : props.options[index.value]
				
			emit("update:value", currentValue)
		}
	}


	watch(() => props.values, (newVal, oldVal) => {
		if (newVal) {
			index.value = props.rangeKey ? props.options.findIndex(item => item[props.rangeValue] == newVal) : props.options.findIndex(item => item == newVal);
		}

	})
</script>